<template>
  <div class="apply-refund">
    <div class="back-btn-mask">
      <div class="back-btn" @click="$router.back()">
        <i class="el-icon-arrow-left"></i>
        返回
      </div>
    </div>
    <div style="height: 33px"></div>
    <el-steps
      :space="300"
      :active="stepsActive"
      align-center
      finish-status="success"
    >
      <el-step title="申请退款"></el-step>
      <el-step title="卖家处理退款申请"></el-step>
      <el-step title="卖家已拒绝" v-if="refundInfo?.status == 3"></el-step>
      <el-step title="买家退货" v-else></el-step>
      <el-step title="退款完成"></el-step>
    </el-steps>
    <div style="height: 33px"></div>
    <div style="display: flex">
      <div style="border: 1px solid #e8e8e8; padding: 20px; flex: 1">
        <template v-if="refundInfo">
          <!-- 申请状态：0->待处理；1->退货中；2->已完成；3->已拒绝; 4->仅退款 -->
          <div
            v-if="(refundInfo.status == 0 || refundInfo.status == 3) && !modifiable"
            style="text-align: center; padding-top: 90px"
          >
            <div style="font-size: 18px; font-weight: 700; color: #000">
              {{ refundInfo.status == 3 ? '商家拒绝退款申请' : '请等待商家处理' }}
            </div>
            <div style="font-size: 14px; color: #999; padding-top: 10px">
              {{ refundInfo.status == 3 ? '原因：' + refundInfo.rejectReason : '您已成功发起退款申请，请耐心等待商家处理' }}
            </div>
            <div style="padding-top: 30px" v-if="refundInfo.status != 3">
              <el-button round @click="handleCancel">撤销申请</el-button>
              <el-button type="danger" round @click="handleModify"
                >修改申请</el-button
              >
            </div>
          </div>
        </template>
        <template v-if="modifiable || !refundInfo">
          <RefundForm
            ref="refoundFormRef"
            :goods-info="orderDetail"
            @submit="handleSubmit"
          ></RefundForm>
        </template>
        <template
          v-if="
            refundInfo && (refundInfo.status == 1 || refundInfo.status == 6)
          "
        >
          <logisticsForm
            @submit="handleSubmitLogistics"
            :refund-info="refundInfo"
            :countdown="countdown"
            :business-address="businessAddress"
          ></logisticsForm>
        </template>

        <template v-if="refundInfo && refundInfo.status == 2">
          <el-result
            icon="success"
            title="退款成功"
            :subTitle="`退款成功时间：${formatTime(refundInfo.handleTime)}`"
          >
          </el-result>
        </template>
      </div>

      <div
        style="
          width: 35%;
          padding: 20px;
          box-sizing: border-box;
          border-top: 1px solid #e8e8e8;
          border-right: 1px solid #e8e8e8;
          border-bottom: 1px solid #e8e8e8;
        "
      >
        <div>
          退款详情
          <div style="display: flex; padding-top: 20px; padding-bottom: 6px">
            <el-image
              :src="orderDetail.productPic"
              style="
                width: 80px;
                height: 80px;
                border-radius: 10px 10px 10px 10px;
              "
              :preview-src-list="[orderDetail.productPic]"
            ></el-image>
            <div
              style="
                line-height: normal;
                display: flex;
                flex-direction: column;
                justify-content: space-around;
                margin-left: 10px;
              "
            >
              <div>{{ orderDetail.productName }}</div>
              <div>×{{ orderDetail.productQuantity }}</div>
              <div>￥{{ orderDetail.productPrice }}</div>
            </div>
          </div>
          <el-divider></el-divider>
          <el-descriptions :column="1">
            <el-descriptions-item label="卖家">{{
              orderDetail.storeName
            }}</el-descriptions-item>
            <el-descriptions-item label="订单编号">{{
              orderDetail.platformOrderSn
            }}</el-descriptions-item>
            <el-descriptions-item label="成交时间">{{
              formatTime(orderDetail.createTime)
            }}</el-descriptions-item>
            <el-descriptions-item label="单价"
              >￥{{ orderDetail.productPrice }} ×
              {{ orderDetail.productQuantity }}(数量)</el-descriptions-item
            >
            <el-descriptions-item label="商品总价"
              >￥{{ orderDetail.productPrice * orderDetail.productQuantity }}
            </el-descriptions-item>
          </el-descriptions>
          <template v-if="refundInfo">
            <el-divider></el-divider>
            <el-descriptions :column="1">
              <el-descriptions-item label="退款编号">{{
                refundInfo.id
              }}</el-descriptions-item>
              <el-descriptions-item label="原因">{{
                refundInfo.reason
              }}</el-descriptions-item>
              <el-descriptions-item label="要求">{{
                refundInfo.serviceType
              }}</el-descriptions-item>
              <el-descriptions-item label="货物状态">{{
                refundInfo.receiveTime === null ? "未收到货" : "已收到货"
              }}</el-descriptions-item>
              <el-descriptions-item label="说明">{{
                refundInfo.description
              }}</el-descriptions-item>
            </el-descriptions>
          </template>
        </div>
        <template v-if="logisticsInfo">
          <el-divider></el-divider>
          <div class="logistics-info">
            物流信息
            <el-timeline>
              <el-timeline-item
                v-for="(activity, index) in activities"
                :key="index"
                :color="activity.color"
                :size="activity.size"
                :timestamp="activity.timestamp"
              >
                {{ activity.content }}
              </el-timeline-item>
            </el-timeline>
          </div>
        </template>
      </div>
    </div>
  </div>
</template>

<script>
import {
  fetchOrderDetail,
  fetchRefundDetail,
  postRefund,
  postModifyRefund,
  postDeleteRefund,
  postSubmitRefundGoods,
  fetchBusinessAddress,
} from "@/api/OrderManagement";
import RefundForm from "../component/RefundForm.vue";
import logisticsForm from "../component/logisticsForm.vue";
import * as dayjs from "dayjs";
export default {
  data() {
    return {
      activities: [
        {
          content: "支持自定义颜色",
          timestamp: "2018-04-03 20:46",
          color: "#07C160",
        },
        {
          content: "支持自定义颜色",
          timestamp: "2018-04-03 20:46",
          color: "#07C160",
        },
      ],
      orderDetail: {},
      refundInfo: null,
      logisticsInfo: null,
      modifiable: false,
      businessAddress: {},
      countdown: "",
    };
  },
  components: {
    RefundForm,
    logisticsForm,
  },
  created() {
    this.getOrderDetail();
    this.$route.query.id &&
      fetchRefundDetail(this.$route.query.id).then((res) => {
        this.refundInfo = res.data;
      });
    // 在组件挂载时开始计算倒计时
    this.calculateCountdown();
    // 每秒更新一次倒计时
    this.timer = setInterval(this.calculateCountdown, 1000);
  },
  beforeDestroy() {
    clearInterval(this.timer);
  },
  computed: {
    stepsActive() {
      return this.refundInfo == null
        ? 0
        : this.refundInfo.status == 0
        ? 1
        : this.refundInfo.status == 1
        ? 2
        : this.refundInfo.status == 2
        ? 4
        : 3;
    },
  },
  methods: {
    formatTime(t) {
      if (!t) return "未知";
      return dayjs(t).format("YYYY-MM-DD HH:mm:ss");
    },
    calculateCountdown() {
      if (!this.refundInfo) return;
      const now = dayjs();
      const target = dayjs(this.refundInfo.handleTime).add(7, "day");
      const diffInSeconds = target.diff(now, "second");

      // 计算剩余的天、小时、分钟和秒
      const days = Math.floor(diffInSeconds / 86400);
      const hours = Math.floor((diffInSeconds % 86400) / 3600);
      const minutes = Math.floor((diffInSeconds % 3600) / 60);
      const seconds = diffInSeconds % 60;

      // 更新倒计时显示
      this.countdown = `${days}天${hours}时${minutes}分${seconds}秒`;

      // 如果目标日期已经过去，清除定时器
      if (now.isAfter(target)) {
        clearInterval(this.timer);
        this.countdown = "倒计时结束";
      }
    },
    getOrderDetail() {
      fetchOrderDetail(this.$route.query.goodsId).then((res) => {
        this.orderDetail = res.data;

        fetchBusinessAddress(res.data.productId).then((res1) => {
          this.businessAddress = res1?.data || {};
        });
      });
    },
    handleSubmit(data) {
      const params = {
        ...data,
        ...this.orderDetail,
        productAttr: this.orderDetail.skuData,
      };
      if (this.modifiable) {
        params.id = this.refundInfo.id;
        postModifyRefund(params).then((res) => {
          this.$message.success("提交成功");
          this.$router.back();
        });
      } else {
        postRefund(params).then((res) => {
          this.$message.success("提交成功");
          this.$router.back();
        });
      }
    },
    handleSubmitLogistics(data) {
      const pramas = {
        ...data,
        id: this.refundInfo.id,
      };
      postSubmitRefundGoods(pramas).then((res) => {
        this.$message.success("提交成功");
        this.$router.back();
      });
    },
    handleModify() {
      this.modifiable = true;
      this.$nextTick(() => {
        console.log(this.$refs.refoundFormRef);
        this.$refs.refoundFormRef?.handleModify(this.refundInfo);
      });
    },
    handleCancel() {
      this.$confirm("确认撤销申请吗？").then(() => {
        postDeleteRefund(this.refundInfo.id).then((res) => {
          this.$message.success("撤销成功");
          this.$router.back();
        });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.apply-refund {
  font-size: 14px;
  /deep/ .el-step__head.is-success {
    color: #e22a1f;
    border-color: #e22a1f;
  }
  /deep/ .el-step__title.is-success {
    color: #e22a1f;
  }
  /deep/.el-timeline-item__content {
    color: #07c160;
  }
  /deep/.el-timeline {
    padding: 20px 0 0;
  }
  .back-btn-mask {
    width: 77px;
    height: 34px;
    background: linear-gradient(
          135deg,
          transparent 12px,
          #e8e8e8 12px,
          #e8e8e8 100%
        )
        top right,
      linear-gradient(45deg, transparent 12px, #e8e8e8 12px, #e8e8e8 100%)
        bottom right;
    background-size: 100% 50%;
    background-repeat: no-repeat;
    display: flex;
    align-items: center;
    justify-content: center;
    .back-btn {
      width: 75px;
      height: 32px;
      background: linear-gradient(
            135deg,
            transparent 12px,
            #fff 12px,
            #fff 100%
          )
          top right,
        linear-gradient(45deg, transparent 12px, #fff 12px, #fff 100%) bottom
          right;
      background-size: 100% 50%;
      background-repeat: no-repeat;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 14px;
      .el-icon-arrow-left {
        margin-right: 4px;
      }
    }
  }
}
</style>
